/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utfpr.cp.control;

import javax.persistence.EntityManager;
import utfpr.cp.model.EntityManagerHelper;
import utfpr.cp.model.URLTarget;
import utfpr.cp.model.URLTargetDAO;

/**
 *
 * @author Adriano_2
 */
public class TargetControl {
    public static URLTarget getNextDomain() {
        EntityManager em = EntityManagerHelper.getEntityManager();
        URLTargetDAO dao = new URLTargetDAO(em);
        URLTarget target = dao.getNextURL();
        if (!target.exist()) {
            target = dao.getNextURL(true);
        }
        if (target.exist()) {
            EntityManagerHelper.beginTransaction();
            target.setStarted(true);
            EntityManagerHelper.commit();
        }
        return target;
    }
    
    public static boolean cancelStarted(URLTarget target) {
        EntityManager em = EntityManagerHelper.getEntityManager();
        try {
            target = em.merge(target);
            EntityManagerHelper.beginTransaction();
            target.setStarted(false);
            target.setError(false);
            target.setFinished(false);
            EntityManagerHelper.commit();
        } catch (Exception e ) {
            return false;
        }
        return true;
    }
    
    public static boolean setFinished(URLTarget target, boolean hasFinished) {
        EntityManager em = EntityManagerHelper.getEntityManager();
        try {
            target = em.merge(target);
            EntityManagerHelper.beginTransaction();
            target.setFinished(hasFinished);
            EntityManagerHelper.commit();
        } catch (Exception e ) {
            return false;
        }
        return true;
    }
    
    public static boolean setFinished(URLTarget target) {
        return setFinished(target, true);
    }
    
    public static boolean setError(URLTarget target, boolean hasError) {
        EntityManager em = EntityManagerHelper.getEntityManager();
        try {
            target = em.merge(target);
            EntityManagerHelper.beginTransaction();
            target.setError(hasError);
            EntityManagerHelper.commit();
        } catch (Exception e ) {
            return false;
        }
        return true;
    }
    
    public static boolean setError(URLTarget target) {
        return setError(target, true);
    }
}
